/**
 * 
 */
package org.thinkinbunny.control;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


import org.thinkinbunny.json.JSONArray;

/**
 * @author ThinkinBunny
 * @see �������3��������sendPostRequest:��������
 */
public class HttpTools {
	
	

	// sendPostRequest ���Ͷ������󣬽���params��ͨ��post������
	public static boolean sendPostRequest(String path,
			JSONArray jsonArray) throws Exception {
		//		StringBuilder sb = new StringBuilder();
		//		if (params != null && !params.isEmpty()) {
		//			for (Map.Entry<String, String> entry : params.entrySet()) {
		//				sb.append(entry.getKey()).append('=')
		//						.append(URLEncoder.encode(entry.getValue(), enc))
		//						.append('&');
		//			}
		//			sb.deleteCharAt(sb.length() - 1);
		//		}
		byte[] entitydata = jsonArray.toString().getBytes();// �õ�ʵ��Ķ��������
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(5 * 1000);
		conn.setDoOutput(true);// ���ͨ��post�ύ��ݣ����������������������
		// Content-Type: application/x-www-form-urlencoded
		// Content-Length: 38
		conn.setRequestProperty("Content-Type",
				"application/html");
		conn.setRequestProperty("Content-Length",
				String.valueOf(entitydata.length));
		OutputStream outStream = conn.getOutputStream();

	
		outStream.flush();
		outStream.close();
		if (conn.getResponseCode() == 200) {
			// ��ⷢ���Ƿ���ɣ������󷵻ش��벻��200
			return true;
		}
		return false;
	}

	//	public static boolean sendPostRequest(String path,
	//			Map<String, String> params, String enc) throws Exception {
	//		StringBuilder sb = new StringBuilder();
	//		if (params != null && !params.isEmpty()) {
	//			for (Map.Entry<String, String> entry : params.entrySet()) {
	//				sb.append(entry.getKey()).append('=')
	//						.append(URLEncoder.encode(entry.getValue(), enc))
	//						.append('&');
	//			}
	//			sb.deleteCharAt(sb.length() - 1);
	//		}
	//		byte[] entitydata = sb.toString().getBytes();// �õ�ʵ��Ķ��������
	//		URL url = new URL(path);
	//		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	//		conn.setRequestMethod("POST");
	//		conn.setConnectTimeout(5 * 1000);
	//		conn.setDoOutput(true);// ���ͨ��post�ύ��ݣ����������������������
	//		// Content-Type: application/x-www-form-urlencoded
	//		// Content-Length: 38
	//		conn.setRequestProperty("Content-Type",
	//				"application/x-www-form-urlencoded");
	//		conn.setRequestProperty("Content-Length",
	//				String.valueOf(entitydata.length));
	//		OutputStream outStream = conn.getOutputStream();
	//		outStream.write(entitydata);
	//		outStream.flush();
	//		outStream.close();
	//		if (conn.getResponseCode() == 200) {
	//			// ��ⷢ���Ƿ���ɣ������󷵻ش��벻��200
	//			return true;
	//		}
	//		return false;
	//	}

	// InputStream ���ڰ�server�˲�������������ݿ���Ϣ������Ϊinputstream������xml��ݽ���
	public static InputStream getUpdateInputStream(String type) {
		InputStream retInputStream = null;
		URL url;
		try {

			url = new URL(
					"http://192.168.1.101:8080/UserManaSys/AndroidResponseServlt?type="
							+ type);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();

			conn.setRequestMethod("POST");
			conn.setConnectTimeout(3 * 1000);
			retInputStream = conn.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}

		return retInputStream;

	}

	/* DownAllPictures����ͼƬ����������ͼƬ��������·������ */
	public static void DownAllPictures(String picName) {

		InputStream retInputStream = null;
		URL url;
		File file = new File("/mnt/sdcard/foods/");
		if (!file.exists()) {
			file.mkdir();
			// ����Ƿ����foodsĿ¼��û���򴴽�
		}
		file = new File("/mnt/sdcard/foods/" + picName);
		if (!file.exists()) {// ���ͼƬ�Ƿ���ڣ����������أ������������
			try {
				url = new URL("http://192.168.1.101:8080/UserManaSys/Images/"
						+ picName);
				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.setRequestMethod("POST");
				conn.setConnectTimeout(3 * 10000);
				retInputStream = conn.getInputStream();
				ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
				int ch;
				while ((ch = retInputStream.read()) != -1) {
					bytestream.write(ch);
				}
				byte imgdata[] = bytestream.toByteArray();

				File pic = new File("/mnt/sdcard/foods/" + picName);
				//System.out.println("len:" + imgdata.length);
				FileOutputStream outputStream = new FileOutputStream(pic);
				outputStream.write(imgdata);

				outputStream.flush();
				outputStream.close();

			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	}


	/**
	 * InputStreamתString
	 * �����õķ���������һ�������ͬ�����ٿ�������ĺ�����Ȼ������
	 * @param is
	 * @param encode
	 * @return
	 */
	public static String stream2string(InputStream is, String encode) {
		if (is != null) {
			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(is, encode));
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				return sb.toString();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	/**
	 * InputStreamתjsonarray
	 * �˴��ڴ���InputStreamʱ���õķ���������һ������ͬ��ֻ�Ƕ��г�һ�����÷�����ʵ��ʹ��ʱ���뿼��һ��Ч������
	 * ����ת��jsonarray�ı��취ֻ�����ڸ������󣬽ӿ�Ҳ���Լ�д�ģ���ʮ����ղ��ᵼ�³��?��λ����Ī�֣����ײ�Ҫ�����
	 * @param is
	 * @return
	 */
	//    public static String stream2jarray(InputStream is) {
	//        if (is != null) {
	//            StringBuffer sb = new StringBuffer();
	//            byte[] b = new byte[4096];
	//            try {
	//                for(int n;(n=is.read(b))!=-1;){
	//                    sb.append(new String(b,0,n));
	//                }
	//                is.close();
	//                if(sb.charAt(0) == '{'){
	//                    return "["+sb.toString()+"]";
	//                }
	//                else{
	//                    return sb.toString();
	//                }
	//            } catch (IOException e) {
	//                e.printStackTrace();
	//            }
	//        }
	//        return "";
	//    }
	// 
	/**
	 * InputStreamתjsonobject
	 * תjsonobjectʱͬ��ʹ���˱��취�����ײ�Ҫ����������
	 * @param is
	 * @return
	 */
	public static String stream2jobject(InputStream is) {
		if (is != null) {
			StringBuffer sb = new StringBuffer();

			byte[] b = new byte[4096];
			try {
				for(int n;(n=is.read(b))!=-1;){
					sb.append(new String(b,0,n));
				}
				is.close();
				if (sb.charAt(0) == '[') {
					return "{\"jarray\":" + sb.toString() + "}";
				}
				else {
					return sb.toString();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "";
	}

	public static String stream2string(InputStream is) {
		return stream2string(is, "utf-8");
	}

	/**
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] stream2byte(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;
	}
}

